<?php

class LilCurrentArea {
	private $request;
	
	public function initialize($request) {
		$_this = self::getInstance();
		$_this->request = $request;
		
		if (!empty($_this->request->params['admin'])) {
			// set from session if not in params
			if (!empty($_this->request->params['named']['area_id'])) {
				$_this->set('id', $_this->request->params['named']['area_id']);
			} else if (!empty($_this->request->params['named']['area'])) {
				$_this->set(Configure::read('Lil.areaSlugField'), $_this->request->params['named']['area']);
			} else if ($defArea = Configure::read('Lil.defaultArea')) {
				$_this->set(Configure::read('Lil.areaSlugField'), $defArea);
			}
		}
	}
/**
 * Return a singleton instance of the LilPluginRegistry.
 *
 * @return LilPluginRegistry instance
 */
	public static function &getInstance() {
		static $instance = array();
		if (!$instance) {
			$instance[0] =& new LilCurrentArea();
		}
		return $instance[0];
	}
/**
 * set method
 *
 * This functions sets area which is used as selected area in administration.
 *
 * @param string $field
 * @param string $value
 * @return void
 */
	public function set($field, $value = null) {
		if (is_null($value)) {
			App::uses('Validation', 'Utility');
			$value = $field;
			if (is_numeric($field) || Validation::uuid($field)) {
				$field = 'id';
			} else {
				$field = 'slug';
			}
		}
		
		if ($areas = Configure::read('Lil.noAreas')) {
			foreach ($areas as $k => $a) {
				if (($a['Area'][$field] == $value) || ($k == $value)) {
					CakeSession::write('admin.area', $a);
					return true;
				}
			}
			return false;
		} else {
			$Area =& ClassRegistry::init('Lil.Area');
			if ($data = $Area->find('first', array(
				'conditions' => array('Area.' . $field => $value)))
			) {
				CakeSession::write('admin.area', $data);
				return true;
			} else return false;
		}
	}
/**
 * clear method
 *
 * This functions clears admin area.
 *
 * @access public
 * @return void
 */
	public function clear() {
		CakeSession::delete('admin.area');
	}
/**
 * get method
 *
 * This functions returns current area in administration.
 *
 * @param string $id
 * @return array
 */
	public function get($field = null) {
		if ($a = CakeSession::read('admin.area')) {
			if (!empty($field) && isset($a['Area'][$field])) {
				return $a['Area'][$field];
			} else {
				return $a;
			}
		} else {
			return null;
		}
	}
}